package com.shenhaofeng.app.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.shenhaofeng.app.R;


/**
 * 空视图布局，控制数据为空时的ui
 * Created by Administrator on 2016/8/4.
 */
public class EmptyLayout extends FrameLayout {


    private View mEmptyView;

    private View mContentView;

    private TextView mEmptyTv;


    public EmptyLayout(Context context) {
        super(context);
        init(context, null, 0);
    }


    public EmptyLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0);
    }


    public EmptyLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }


    /**
     * 初始化
     *
     * @param context
     * @param attrs
     * @param defStyleAttr
     */
    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        mEmptyView = LayoutInflater.from(context).inflate(R.layout.widget_empty, this, false);
        addView(mEmptyView);
        mEmptyView.setVisibility(View.GONE);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.EmptyLayout, defStyleAttr, 0);
        mEmptyTv = (TextView) mEmptyView.findViewById(R.id.empty_txt);
        mEmptyTv.setText(ta.getText(R.styleable.EmptyLayout_emptyText));
        Drawable emptyDrawable = ta.getDrawable(R.styleable.EmptyLayout_emptySrc);
        ImageView emptyImageView = (ImageView) mEmptyView.findViewById(R.id.empty_img);
        emptyImageView.setImageDrawable(emptyDrawable);
        ta.recycle();
    }


    public void setEmptyText(CharSequence emptyText) {
        mEmptyTv.setText(emptyText);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int count = getChildCount();
        if (count != 2) {
            throw new IllegalStateException("EmptyLayout 必须且只能添加一个子View");
        }
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            if (mEmptyView != child) {
                mContentView = child;
            }
        }
    }


    /**
     * 是否数据为空
     *
     * @param empty
     */
    public void empty(final boolean empty) {
        if (empty) {
            mEmptyView.setVisibility(View.VISIBLE);
        } else {
            mEmptyView.setVisibility(View.GONE);
        }
    }


}
